package com.khalil.kkadmin.system.dms.store.systemfile;

import com.khalil.kkadmin.infrastructure.properties.DmsProperties;
import com.khalil.kkadmin.system.dms.store.DocumentStore;
import com.khalil.kkadmin.system.dms.store.DocumentStoreInfo;
import com.khalil.kkadmin.system.dms.store.StoreType;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

@Service
public class SystemFileDocumentStore implements DocumentStore {

    @Autowired
    private DmsProperties dmsProperties;

    @Override
    public boolean support(StoreType type) {
        return StoreType.SYSTEM_FILE == type;
    }

    @Override
    public DocumentStoreInfo store(DocumentStoreInfo documentStoreInfo) {
        String filename = documentStoreInfo.getFilename();
        List<String> pathArr = documentStoreInfo.getPathArr();
        String targetPath = getTargetPath(pathArr, filename);
        File targetFile = new File(targetPath);
        try {
            FileUtils.forceMkdirParent(targetFile);
            FileUtils.copyInputStreamToFile(documentStoreInfo.getInputStream(), targetFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return documentStoreInfo;
    }

    private String getTargetPath(List<String> pathArr, String filename) {
        String directory = String.join(File.separator, pathArr);
        return dmsProperties.getBasePath() + File.separator + directory + File.separator + filename;
    }

    @Override
    public DocumentStoreInfo getDocumentStoreInfo(List<String> pathArr, String filename) {
        String targetPath = getTargetPath(pathArr, filename);
        File targetFile = new File(targetPath);
        if (targetFile.exists()) {
            try {
                FileInputStream inputStream = FileUtils.openInputStream(targetFile);
                return DocumentStoreInfo.builder()
                        .filename(filename)
                        .pathArr(pathArr)
                        .inputStream(inputStream)
                        .build();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        throw new RuntimeException("文件不存在");
    }

    @Override
    public void delete(List<String> pathArr, String filename) {
        String targetPath = getTargetPath(pathArr, filename);
        File targetFile = new File(targetPath);
        if (targetFile.exists()) {
            boolean deleted = targetFile.delete();
        }
    }
}
